#include "StdAfx.h"
#include "MyPicking.h"

MyPicking::MyPicking(float viewportWidth, float viewportHeight)
{
	this->_viewportWidth = viewportWidth;
	this->_viewportHeight = viewportHeight;

	this->_pickingRay = new PickingRay();
}

void MyPicking::update()
{
	view = cam->GetPosition() - cam->GetTarget();
	view.Normalize();

	position = cam->GetPosition();

	screenHoritzontally = view.Cross(cam->GetUpVector());
	screenHoritzontally.Normalize();

	screenVertically = screenHoritzontally.Cross(view);
	screenVertically.Normalize();


	float halfHeight = (float)((tanf(fov / 2.0f)) * near);
	float halfScaledAspectRatio = halfHeight*aspectRatio;

	screenVertically *= halfHeight;
	screenHoritzontally *= halfScaledAspectRatio;
}

void MyPicking::picking(float screenX, float screenY, LookAtCamera *cam)
{
	this->cam = cam;
	this->update();

	this->_pickingRay->setClickPosInWorld(this->position + this->view);
	screenX -= _viewportWidth / 2.0f;
	screenY -= _viewportHeight / 2.0f;

	screenX /= (_viewportWidth / 2.0f);
	screenY /= (_viewportHeight / 2.0f);

	Vector3 newpos;
	newpos.x = _pickingRay->getClickPosInWorld().x + screenHoritzontally.x*screenX + screenVertically.x*screenY;
	newpos.y = _pickingRay->getClickPosInWorld().y + screenHoritzontally.y*screenX + screenVertically.y*screenY;
	newpos.z = _pickingRay->getClickPosInWorld().z + screenHoritzontally.z*screenX + screenVertically.z*screenY;

	_pickingRay->setClickPosInWorld(newpos);

	_pickingRay->setDirection(_pickingRay->getClickPosInWorld() - position);

	esLogMessage("picking completed!\n");
	esLogMessage("pos %f %f %f \n", _pickingRay->getClickPosInWorld().x, _pickingRay->getClickPosInWorld().y, _pickingRay->getClickPosInWorld().z);
	esLogMessage("dir %f %f %f \n", _pickingRay->getDirection().x, _pickingRay->getDirection().y, _pickingRay->getDirection().z);
}